// pages/dynamic/index.js
const util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dynamiclist: [],
    currentkey: ''
  },
  goDynamicForm: function () {
    wx.navigateTo({
      url: '/pages/dynamicForm/index',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  getDynamicList() {
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.init({
      env: 'cloud1-5glocnmp62950062'
    })
    wx.cloud.callFunction({
      name: 'getDynamic',
      success: (res) => {
        console.log(res)
        wx.hideLoading({
          success: (res) => {},
        })
        let dynamicData = res.result.dynamiclist.list.reverse().map(item => {
          item.title = util.subStrFormat(item.title, 16)
          item.like = item.love.length
          return item
        })
        this.setData({
          dynamiclist: dynamicData
        })
        console.log(this.data.dynamiclist)
      },
      fail: function (err) {
        wx.showToast({
          title: '获取数据失败，请稍后再试',
          icon: 'none',
        })
        console.error(err)
      },
      complete: res => {}
    })
  },
  getsearchResult(e) {
    let searchkey = e.detail
    if(searchkey===''){
      this.getDynamicList()
      return
    }
    wx.showLoading({
      title: '加载中，请稍后',
    })
      

      this.setData({
        currentkey:searchkey
      })
    wx.cloud.init({
      env: 'cloud1-5glocnmp62950062'
    })
    console.log(this.data.currentkey)
    
    wx.cloud.callFunction({
      name: 'searchDynamic',
      data: {
        key: this.data.currentkey
      },
      success: res => {
        let dynamicData = res.result.dynamiclist.data.reverse().map(item => {
          item.title = util.subStrFormat(item.title, 16)
          item.like = false
          return item
        })
        this.setData({
          dynamiclist: dynamicData
        })
        wx.hideLoading()
      },
      fail:res=>{
        wx.hideLoading()
        console.error(res)
        wx.showToast({
          title: '加载失败，请稍后再试',
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getDynamicList()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onPullDownRefresh: function () {

    this.getDynamicList()
    wx.stopPullDownRefresh()
  }
})